package com.yjt.flowable.config;

import com.yjt.common.exceptions.AuthExceptionEntryPoint;
import com.yjt.common.exceptions.CustomAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

import javax.annotation.Resource;

import static com.yjt.common.constant.ComConstant.COMMON_PASS_PATH;
import static com.yjt.common.constant.ComConstant.FLOWABLE_RESOURCE_ID;

/**
 * 资源配置文件
 *
 * @author zzp
 * @version 1.0
 **/
@Configuration
@EnableResourceServer
public class ResouceServerConfig extends ResourceServerConfigurerAdapter {


    @Autowired
    TokenStore tokenStore;

    @Resource
   private AuthExceptionEntryPoint authExceptionEntryPoint;

    @Resource
    private CustomAccessDeniedHandler customAccessDeniedHandler;

    /**
     * 当前资源需要放过的路径
     */
    public static String[] SERVICE_PASS_PATH = {};

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources
                //资源 id
                .resourceId(FLOWABLE_RESOURCE_ID)
                .tokenStore(tokenStore)
                .authenticationEntryPoint(authExceptionEntryPoint)
                .accessDeniedHandler(customAccessDeniedHandler)
                .stateless(true);
    }

    //安全管理配置
    @Override
    public void configure(HttpSecurity http) throws Exception {
        //配置直接通过的资源url
        http
                .authorizeRequests()
                .antMatchers(COMMON_PASS_PATH).permitAll()
                .antMatchers(SERVICE_PASS_PATH).permitAll()
                .antMatchers("/**")
                .access("#oauth2.hasScope('ROLE_ADMIN')")
                .and().csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}
